using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using System.ComponentModel.DataAnnotations;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 表单管理控制器
    /// 提供表单的增删改查、提交管理、字段配置等功能的 RESTful API
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class FormsController : ControllerBase
    {
        private readonly IFormAppService _formService;
        private readonly ILogger<FormsController> _logger;

        public FormsController(
            IFormAppService formService,
            ILogger<FormsController> logger)
        {
            _formService = formService;
            _logger = logger;
        }

        /// <summary>
        /// 分页获取表单列表
        /// 支持关键词搜索和状态筛选的分页查询功能
        /// </summary>
        /// <param name="pageIndex">页码，从1开始</param>
        /// <param name="pageSize">每页显示数量，默认20</param>
        /// <param name="keyword">搜索关键词，用于表单名称和描述的模糊匹配</param>
        /// <param name="status">表单状态筛选，可选值见FormStatus枚举</param>
        /// <returns>分页的表单列表数据</returns>
        /// <response code="200">返回分页表单列表</response>
        /// <response code="401">未授权访问</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<PagedResultDto<FormDto>>> GetPaged(
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20,
            [FromQuery] string? keyword = null,
            [FromQuery] byte? status = null)
        {
            try
            {
                var (items, total) = await _formService.GetPagedAsync(pageIndex, pageSize, keyword, status);
                return Ok(new PagedResultDto<FormDto>(items, total, pageIndex, pageSize));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting paged forms");
                return BadRequest(new { message = ex.Message });
            }
        }

        // 全量
        [HttpGet("all")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<IEnumerable<FormDto>>> GetAll()
        {
            try
            {
                var result = await _formService.GetAllAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting all forms");
                return BadRequest(new { message = ex.Message });
            }
        }

        // 活跃表单
        [HttpGet("active")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<IEnumerable<FormDto>>> GetActive()
        {
            try
            {
                var result = await _formService.GetActiveFormsAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting active forms");
                return BadRequest(new { message = ex.Message });
            }
        }

        // 按ID
        [HttpGet("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        [AllowAnonymous]
        public async Task<ActionResult<FormDto>> GetById(long id)
        {
            try
            {
                var result = await _formService.GetByIdAsync(id);
                if (result == null) return NotFound();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting form {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 按标识符
        [HttpGet("identifier/{identifier}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        [AllowAnonymous]
        public async Task<ActionResult<FormDto>> GetByIdentifier(string identifier)
        {
            try
            {
                var result = await _formService.GetByIdentifierAsync(identifier);
                if (result == null) return NotFound();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting form by identifier {Identifier}", identifier);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 搜索
        [HttpGet("search")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<PagedResultDto<FormDto>>> Search(
            [FromQuery][Required] string keyword,
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                var (items, total) = await _formService.GetPagedAsync(pageIndex, pageSize, keyword, null);
                return Ok(new PagedResultDto<FormDto>(items, total, pageIndex, pageSize));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error searching forms with keyword {Keyword}", keyword);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 创建
        [HttpPost]
        [ProducesResponseType(201)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<FormDto>> Create([FromBody] FormDto dto)
        {
            try
            {
                var created = await _formService.CreateAsync(dto);
                return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating form");
                return BadRequest(new { message = ex.Message });
            }
        }

        // 更新
        [HttpPut("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<FormDto>> Update(long id, [FromBody] FormDto dto)
        {
            try
            {
                dto.Id = id;
                var updated = await _formService.UpdateAsync(dto);
                return Ok(updated);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating form {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 删除
        [HttpDelete("{id:long}")]
        [ProducesResponseType(200)]
        public async Task<ActionResult> Delete(long id)
        {
            try
            {
                var ok = await _formService.DeleteAsync(id);
                return ok ? Ok(new { success = true }) : BadRequest(new { success = false });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting form {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 批量删除
        [HttpPost("batch-delete")]
        [ProducesResponseType(200)]
        public async Task<ActionResult> BatchDelete([FromBody] BatchDeleteRequest request)
        {
            try
            {
                var deleted = await _formService.BatchDeleteAsync(request.Ids);
                return Ok(new { success = true, count = deleted });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error batch deleting forms");
                return BadRequest(new { message = ex.Message });
            }
        }

        // 更新状态
        [HttpPut("{id:long}/status")]
        [ProducesResponseType(200)]
        public async Task<ActionResult> UpdateStatus(long id, [FromQuery][Required] byte status)
        {
            try
            {
                var ok = await _formService.UpdateStatusAsync(id, status);
                return ok ? Ok(new { success = true }) : BadRequest(new { success = false });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating form status {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 复制
        [HttpPost("{id:long}/duplicate")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<FormDto>> Duplicate(long id, [FromQuery][Required] string newName, [FromQuery][Required] string newIdentifier)
        {
            try
            {
                var duplicated = await _formService.DuplicateAsync(id, newName, newIdentifier);
                return Ok(duplicated);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error duplicating form {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 标识符是否存在
        [HttpGet("identifier-exists")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<object>> IdentifierExists([FromQuery][Required] string identifier, [FromQuery] long? excludeId = null)
        {
            try
            {
                var exists = await _formService.IdentifierExistsAsync(identifier, excludeId);
                return Ok(new { exists });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error checking identifier exists {Identifier}", identifier);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 提交表单
        [HttpPost("{formId:long}/submit")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<object>> Submit(long formId, [FromBody] Dictionary<string, object> data)
        {
            try
            {
                var ua = Request.Headers["User-Agent"].ToString();
                var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                var result = await _formService.SubmitFormDataAsync(formId, data, ua, ip);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error submit form {FormId}", formId);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 提交列表
        [HttpGet("{formId:long}/submissions")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<PagedResultDto<object>>> GetSubmissions(long formId, [FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 20)
        {
            try
            {
                var (items, total) = await _formService.GetFormSubmissionsAsync(formId, pageIndex, pageSize);
                return Ok(new PagedResultDto<object>(items, total, pageIndex, pageSize));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting form submissions {FormId}", formId);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 导出
        [HttpGet("{formId:long}/export")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> Export(long formId, [FromQuery] string format = "excel")
        {
            try
            {
                var path = await _formService.ExportFormSubmissionsAsync(formId, format);
                return Ok(new { path });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error exporting form submissions {FormId}", formId);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 统计
        [HttpGet("{formId:long}/stats")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> GetStatistics(long formId)
        {
            try
            {
                var stats = await _formService.GetFormStatisticsAsync(formId);
                return Ok(stats);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting form statistics {FormId}", formId);
                return BadRequest(new { message = ex.Message });
            }
        }

        // 清理过期提交
        [HttpPost("cleanup-expired")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> CleanupExpired([FromQuery] int daysToKeep = 365)
        {
            try
            {
                var count = await _formService.CleanupExpiredSubmissionsAsync(daysToKeep);
                return Ok(new { success = true, count });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error cleaning up expired submissions");
                return BadRequest(new { message = ex.Message });
            }
        }

        // 校验配置
        [HttpPost("validate")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<object>> Validate([FromBody] FormDto dto)
        {
            try
            {
                var (isValid, errors) = await _formService.ValidateFormConfigurationAsync(dto);
                return Ok(new { isValid, errors });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error validating form configuration");
                return BadRequest(new { message = ex.Message });
            }
        }

        // 预览
        [HttpGet("{id:long}/preview")]
        [ProducesResponseType(200)]
        [AllowAnonymous]
        public async Task<ActionResult<object>> Preview(long id)
        {
            try
            {
                var html = await _formService.PreviewFormAsync(id);
                return Ok(new { html });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error previewing form {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }
    }

}
